package de.se.ludoapp.activity.task;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.PlayerTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameListResponse;

/**
 * Task to get all open games from the server.
 * 
 * @author Marlen Rotert
 * 
 */
public class OpenGamesTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private PlayerTableActivity context;
	private ArrayList<Game> gamelist;

	public OpenGamesTask(LudoApplication ludoApp, PlayerTableActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.gamelist = null;
	}

	/**
	 * OpenGames from Server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute getFreeGames */
		GameListResponse gameListResponse = ludoApp.getLudoStub()
				.getFreeGames();
		if (gameListResponse.getReturnCode() == 0) {
			gamelist = gameListResponse.getGamelist();
		}
		return gameListResponse.getMsg();
	}

	/**
	 * Show open games as list. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (gamelist != null) {
			ListAdapter adapter = new ArrayAdapter(context,
					android.R.layout.simple_list_item_1, gamelist);
			ListView listViewOpenGames = (ListView) context
					.findViewById(R.id.listViewOpenGames);
			listViewOpenGames.setAdapter(adapter);
		} else {
			TextView textView = (TextView) context
					.findViewById(R.id.listViewOpenGames);
			textView.setText(textView.getText() + " " + result);
		}
	}
}
